package com.lt.common;

import android.content.SharedPreferences;
import android.provider.Settings;
import android.text.TextUtils;

import com.lt.base.BaseApplication;
import com.lt.LibConstant;

import java.io.UnsupportedEncodingException;
import java.util.UUID;

/**
 * 返回android唯一的客户端ID
 *
 * @author luotian
 */
public class DeviceUuidFactory {
    private static final String PREFS_FILE = "device_id.xml";
    private static final String PREFS_DEVICE_ID = "device_id";
    private static UUID uuid;

    private static DeviceUuidFactory instance;

    public static DeviceUuidFactory getInstance() {
        if (instance == null) {
            synchronized (DeviceUuidFactory.class) {
                instance = new DeviceUuidFactory();
            }
        }
        return instance;
    }

    private DeviceUuidFactory() {
        if (uuid == null) {
            synchronized (DeviceUuidFactory.class) {
                final SharedPreferences prefs = BaseApplication.getContext().getSharedPreferences(PREFS_FILE, 0);
                if (uuid == null) {
                    final String id = prefs.getString(PREFS_DEVICE_ID, null);
                    if (id != null) {
                        //如果配置文件不为空，则使用配置文件里的UID
                        uuid = UUID.fromString(id);
                    } else {
//                        final String androidId = Secure.getString(
//                                BaseApplication.getContext().getContentResolver(), Secure.ANDROID_ID);
                        final String androidId = Settings.System.getString(BaseApplication.getContext().getContentResolver(), Settings.Secure.ANDROID_ID);
                        try {
                            if (!TextUtils.isEmpty(androidId) && !"9774d56d682e549c".equals(androidId)) {
                                uuid = UUID.nameUUIDFromBytes(androidId.getBytes(LibConstant.UTF_8));
                            } else {
                                // 如果系统拿到的id为空或者错误，随机生成一个id
                                uuid = UUID.randomUUID();
                            }
                        } catch (UnsupportedEncodingException e) {
                            throw new RuntimeException(e);
                        }
                        if (uuid != null) {
                            //写入配置文件
                            prefs.edit().putString(PREFS_DEVICE_ID, uuid.toString()).apply();
                        }
                    }
                }
            }
        }
    }

    /**
     * Returns a unique UUID for the current android device. As with all UUIDs,
     * this unique ID is "very highly likely" to be unique across all Android
     * devices. Much more so than ANDROID_ID is.
     * <p>
     * The UUID is generated by using ANDROID_ID as the base key if appropriate,
     * falling back on TelephonyManager.getDeviceID() if ANDROID_ID is known to
     * be incorrect, and finally falling back on a random UUID that's persisted
     * to SharedPreferences if getDeviceID() does not return a usable value.
     * <p>
     * In some rare circumstances, this ID may change. In particular, if the
     * device is factory reset a new device ID may be generated. In addition, if
     * a user upgrades their phone from certain buggy implementations of Android
     * 2.2 to a newer, non-buggy version of Android, the device ID may change.
     * Or, if a user uninstalls your app on a device that has neither a proper
     * Android ID nor a Device ID, this ID may change on reinstallation.
     * <p>
     * Note that if the code falls back on using TelephonyManager.getDeviceId(),
     * the resulting ID will NOT change after a factory reset. Something to be
     * aware of.
     * <p>
     * Works around a bug in Android 2.2 for many devices when using ANDROID_ID
     * directly.
     *
     * @return a UUID that may be used to uniquely identify your device for most
     * purposes.
     */
    public UUID getDeviceUuid() {
        return uuid;
    }

    public String getDeviceId() {
        return uuid != null ? uuid.toString() : LibConstant.unknown;
    }


}
